package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * 通过反射机制调用方法
 */
public class ReflectDemo4 {
    public static void main(String[] args) throws Exception {
//        //1.实例化Class对象
//        Class cls = Class.forName("reflect.Person");
//        //2.调用无参构造方法实例化Person对象,相当于:Object obj = new Person();
//        Object obj = cls.newInstance();
//        //3.通过类对象获取sayHello方法
//        Method method = cls.getMethod("sayHello");
//        //4.通过方法对象的invoke来调用sayHello方法,
//        method.invoke(obj);

        Scanner scan = new Scanner(System.in);
        System.out.println("请输入一个类名:");
        String className = scan.nextLine();
        System.out.println("请输入一个方法名:");
        String methodName = scan.nextLine();

        Class cls = Class.forName(className);
        Constructor constructor = cls.getConstructor(String.class);
        Object obj = constructor.newInstance("赵四");
        Method method = cls.getMethod(methodName);
        method.invoke(obj);


    }
}
